package com;

import hh.util.Recorder;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Redis {
    static long i = 0;
    static JedisPool jedis = getJedis();
    static Recorder recorder = new Recorder(false, 1000);

    public static void main(String[] args) throws Exception {


        Jedis resource = jedis.getResource();
        for (int j = 0; j < 5; j++) {
            long s = System.nanoTime();
            resource.set("asdf" + i,"asdf" + i);
            System.out.println(System.nanoTime()-s);
        }


        int conc = args.length == 0 ? 10 : Integer.parseInt(args[0]);
        System.out.println("并发度："+conc);
        ExecutorService p = Executors.newFixedThreadPool(conc);
        for (int j = 0; j < conc; j++) {
            if(j%2==0)p.execute(Redis::get);
            else p.execute(Redis::set);
        }

    }

    private static void get() {
        int j = 0;
        Jedis resource = jedis.getResource();
        while (true) {
            long s = System.currentTimeMillis();
            resource.get("asdfadsf" + j++);
            String record = recorder.record(1);
            if(record!=null) System.out.print("get="+(System.currentTimeMillis()-s));
        }
    }

    private static void set() {
        Jedis resource = jedis.getResource();
        int j = 0;
        while (true) {
            j++;
            long s = System.currentTimeMillis();
            resource.set("asdfadsf" + j, "asdfadsf" + j);
            String record = recorder.record(1);
            if(record!=null) System.out.print("set="+(System.currentTimeMillis()-s));
        }
    }

    private static JedisPool getJedis() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(100);
        config.setMaxIdle(100);

        String host = "192.168.8.116";
//        String host = "localhost";
        return new JedisPool(host, 6379);
    }
}
